package com.gosling.cloudspace.config.web;

import com.gosling.cloudspace.common.annotation.JwtIgnore;
import com.gosling.cloudspace.tools.JwtTokenTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

public class AuthenticationInterceptor implements HandlerInterceptor {
    protected static final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从http请求头中取出token
        final String token = request.getHeader(JwtTokenTool.AUTH_HEADER_KEY);
        //如果不是映射到方法，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //如果是方法探测，直接通过
        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String uri = request.getRequestURI();
        if (uri.contains("login/in")) {
//         //验证，并获取token内部信息
//         UserInfoPO userToken = JwtTokenTool.verifyToken(token);
//         //将token放入本地缓存
//         WebContextUtil.setUserToken(userToken);
            //如果方法有JwtIgnore注解，直接通过
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(JwtIgnore.class)) {
                JwtIgnore jwtIgnore = method.getAnnotation(JwtIgnore.class);
                if (jwtIgnore.value()) {
                    logger.info("无需权限验证！");
                    return true;
                }
            }
            if (Objects.isNull(token)) {
                logger.info("token为空，鉴权失败！");
                return false;
            }
            return true;
        }
        return true;
    }

//   @Override
//   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//      //方法结束后，移除缓存的token
//      WebContextUtil.removeUserToken();
//   }
}